﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Support;
//using GemBox.Spreadsheet;
using System.Collections;

namespace CMS_GYM
{
    public partial class hsDataGrid : DataGrid
    {
        //──────────────────────────────────────────────────────────────────   

        public DataView dvSource;
        public int RowCount;
        public int ColumnCount;
        public bool allowNew = false;
        public bool allowDelete = false;
        public bool allowUpdate = true;
        public List<UserControls.rowColor> lstRowColor;
        public List<ColumnView> lstColumn;
        
        public string ColName;
        private bool isPaint = false;
        public ContextMenuStrip popupMenu;
        public ToolStripMenuItem mnDeleteChosenRow;
        public ToolStripMenuItem mnDeleteOhterRow;
        public ToolStripMenuItem mnExportToExel;
        




        //──────────────────────────────────────────────────────────────────   
        public hsDataGrid()
        {
            InitializeComponent();
            dvSource = null;
            this.lstRowColor = null;
            lstColumn = null;
            #region Tạo mẫu hiện thị
            this.AlternatingBackColor = System.Drawing.Color.Black;
            this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.BackColor = System.Drawing.Color.GhostWhite;
            this.BackgroundColor = System.Drawing.SystemColors.Window;
            this.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.CaptionBackColor = System.Drawing.SystemColors.GrayText;
            this.CaptionForeColor = System.Drawing.SystemColors.Window;
            this.DataMember = "";
            this.FlatMode = true;
            this.Font = new System.Drawing.Font("Arial", 9F);
            this.ForeColor = System.Drawing.Color.Black;
            this.GridLineColor = System.Drawing.SystemColors.InactiveCaptionText;
            this.HeaderBackColor = System.Drawing.SystemColors.Control;
            this.HeaderFont = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold);
            this.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.LinkColor = System.Drawing.Color.Teal;
            this.Location = new System.Drawing.Point(3, 0);
            this.Name = "dgView";
            this.ParentRowsBackColor = System.Drawing.Color.Lavender;
            this.ParentRowsForeColor = System.Drawing.Color.Black;
            this.SelectionBackColor = System.Drawing.Color.Teal;
            this.SelectionForeColor = System.Drawing.Color.Black;
            #endregion

            #region Tạo menu
            popupMenu = new ContextMenuStrip();
            mnExportToExel = new ToolStripMenuItem("Xuất ra File Excel");
            mnExportToExel.Click += new EventHandler(mnExportToExel_Click);
            mnDeleteChosenRow = new ToolStripMenuItem("Xóa các dòng đã chọn");
            mnDeleteChosenRow.Click += new EventHandler(mnDeleteChosenRow_Click);
            mnDeleteOhterRow = new ToolStripMenuItem("Xóa các dòng không chọn");
            mnDeleteOhterRow.Click += new EventHandler(mnDeleteOhterRow_Click);
            mnDeleteOhterRow.Visible = false;
            mnDeleteChosenRow.Visible = false;

            ToolStripMenuItem mnColor = new ToolStripMenuItem("Chọn màu hiện thị");
            mnColor.Click += new EventHandler(mnColor_Click);
            popupMenu.Items.AddRange(new ToolStripItem[] { mnExportToExel, mnColor, mnDeleteChosenRow, mnDeleteOhterRow });
            this.ContextMenuStrip = popupMenu;
            #endregion
            this.DataSourceChanged += new EventHandler(hsDataGrid_DataSourceChanged);
            this.SizeChanged += new EventHandler(hsDataGrid_SizeChanged);

        }


        //──────────────────────────────────────────────────────────────────   
        void hsDataGrid_SizeChanged(object sender, EventArgs e)
        {
            if (this.lstColumn != null && dvSource != null)
                this.setViewStyle(lstColumn, dvSource);

        }
        //──────────────────────────────────────────────────────────────────   
        void mnColor_Click(object sender, EventArgs e)
        {
            UserControls.frmColorDataGrid F = new UserControls.frmColorDataGrid();
            UserControls.frmColorDataGrid.cCaptionColor = this.CaptionBackColor;
            UserControls.frmColorDataGrid.cHeaderColor = this.HeaderBackColor;
            UserControls.frmColorDataGrid.cBackColor = this.BackColor;
            UserControls.frmColorDataGrid.cAlternatingBackColor = this.AlternatingBackColor;
            UserControls.frmColorDataGrid.cBackgroundColor = this.BackgroundColor;
            UserControls.frmColorDataGrid.cForeColor = this.ForeColor;
            UserControls.frmColorDataGrid.cLineColor = this.GridLineColor;
            UserControls.frmColorDataGrid.cSelectedColor = this.SelectionForeColor;
            UserControls.frmColorDataGrid.cSelectedBackColor = this.SelectionBackColor;
            UserControls.frmColorDataGrid.cHeaderForeColor = this.HeaderForeColor;
            UserControls.frmColorDataGrid.cCaptionForeColor = this.CaptionForeColor;
            F.ShowDialog();

            this.CaptionBackColor = UserControls.frmColorDataGrid.cCaptionColor;
            this.HeaderBackColor = UserControls.frmColorDataGrid.cHeaderColor;
            this.BackColor = UserControls.frmColorDataGrid.cBackColor;
            this.AlternatingBackColor = UserControls.frmColorDataGrid.cAlternatingBackColor;
            this.BackgroundColor = UserControls.frmColorDataGrid.cBackgroundColor;
            this.ForeColor = UserControls.frmColorDataGrid.cForeColor;
            this.GridLineColor = UserControls.frmColorDataGrid.cLineColor;
            this.SelectionForeColor = UserControls.frmColorDataGrid.cSelectedColor;

            this.SelectionBackColor = UserControls.frmColorDataGrid.cSelectedBackColor;
            this.HeaderForeColor = UserControls.frmColorDataGrid.cHeaderForeColor;
            this.CaptionForeColor = UserControls.frmColorDataGrid.cCaptionForeColor;

            if (this.TableStyles.Count > 0)
            {
                DataGridTableStyle dgTableStyle = this.TableStyles[0];
                dgTableStyle.ForeColor = this.ForeColor;
                dgTableStyle.HeaderBackColor = this.HeaderBackColor;
                dgTableStyle.HeaderForeColor = this.HeaderForeColor;
                dgTableStyle.GridLineColor = this.GridLineColor;
                dgTableStyle.SelectionBackColor = this.SelectionBackColor;
                dgTableStyle.SelectionForeColor = this.SelectionForeColor;
                dgTableStyle.AlternatingBackColor = this.AlternatingBackColor;
                dgTableStyle.HeaderForeColor = this.HeaderForeColor;
                dgTableStyle.SelectionBackColor = this.SelectionBackColor;


            }




        }
        //──────────────────────────────────────────────────────────────────   
        void hsDataGrid_DataSourceChanged(object sender, EventArgs e)
        {
            if (this.DataSource == null) return;
            //DataTable dt = null;
            if (this.DataSource.GetType().ToString() == "System.Data.DataView")
                dvSource = (DataView)this.DataSource;
            else dvSource = ((DataTable)this.DataSource).DefaultView;
            this.RowCount = dvSource.Count;
            this.ColumnCount = dvSource.Table.Columns.Count;
            string s = this.CaptionText;
            int pos = s.IndexOf(" ,Số lượng: ");
            if (pos != -1) s = s.Remove(pos, s.Length - pos);
            s += " ,Số lượng: " + dvSource.Count.ToString();
            this.CaptionText = s;
            

        }
        //──────────────────────────────────────────────────────────────────   
        //public void ExportToExel()
        //{

        //    #region Kiểm tra dữ liệu và mở hộp thoại Save dialog
        //    if (dvSource == null || dvSource.Count == 0) return;
        //    SaveFileDialog dlg = new SaveFileDialog();
        //    dlg.ShowDialog();
        //    if (dlg.FileName == null || dlg.FileName == "") return;
        //    DataTable dt = dvSource.ToTable();
        //    DataTable dtHead = new DataTable();
        //    #endregion
        //    #region Trường hợp Đã có tableStyle
        //    if (this.TableStyles.Count > 0)
        //    {
        //        List<string> lstColumnName = new List<string>();
        //        for (int i = 0; i < dt.Columns.Count; i++)
        //            lstColumnName.Add(dt.Columns[i].ColumnName);

        //        for (int p = 0; p < lstColumnName.Count; p++)
        //            if (!this.ExistColumns(lstColumnName[p]))
        //                dt.Columns.Remove(lstColumnName[p]);

        //        List<string> lstNewColumnName = new List<string>();
        //        for (int column = 0; column < this.TableStyles[0].GridColumnStyles.Count; column++)
        //            if (dt.Columns.IndexOf(this.TableStyles[0].GridColumnStyles[column].MappingName) != -1)
        //                lstNewColumnName.Add(this.TableStyles[0].GridColumnStyles[column].MappingName);


        //        for (int j = lstNewColumnName.Count - 1; j > 0; j--)
        //            dt.Columns[lstNewColumnName[j]].SetOrdinal(j);



        //        for (int r = 0; r < lstNewColumnName.Count; r++)
        //            dtHead.Columns.Add(lstNewColumnName[r], this.CaptionText.GetType());
        //        DataRow dr = dtHead.NewRow();
        //        for (int row = 0; row < lstNewColumnName.Count; row++)
        //            dr[lstNewColumnName[row]] = this.TableStyles[0].GridColumnStyles[lstNewColumnName[row]].HeaderText;
        //        dtHead.Rows.Add(dr);

        //    }
        //    #endregion
        //    #region Không có một TableStyle nào cả
        //    else
        //    {
        //        for (int p = 0; p < dt.Columns.Count; p++)
        //            dtHead.Columns.Add(dt.Columns[p].ColumnName, this.CaptionText.GetType());
        //        DataRow drNew = dtHead.NewRow();
        //        for (int p1 = 0; p1 < dt.Columns.Count; p1++)
        //            drNew[p1] = dt.Columns[p1].ColumnName;
        //        dtHead.Rows.Add(drNew);
        //    }
        //    #endregion
        //    #region Xuất ra file Exel
        //    //GemBox.Spreadsheet.SpreadsheetInfo.SetLicense("EDWF-XKP8-D7YQ-ZTD6");
        //    //ExcelFile exFile = new ExcelFile();
        //    //ExcelWorksheetCollection worksheets = exFile.Worksheets;


        //    int numberSubsTable = 0;
        //    if (dt.Rows.Count % 65000 == 0)
        //        numberSubsTable = dt.Rows.Count / 65000;
        //    else
        //        numberSubsTable = dt.Rows.Count / 65000 + 1;

        //    for (int number = 0; number <= numberSubsTable; number++)
        //    {
        //        DataTable dtTemp = dt.Copy();
        //        dtTemp.Clear();
        //        int PosHead = number * 65000;
        //        int PosTail = PosHead + 65000;
        //        if (PosTail >= dt.Rows.Count - 1) PosTail = dt.Rows.Count - 1;
        //        for (int i = PosHead; i <= PosTail; i++)
        //        {
        //            object[] arrOb = dt.Rows[i].ItemArray;
        //            dtTemp.Rows.Add(arrOb);
        //        }
        //        worksheets.Add("File" + number.ToString());
        //            worksheets[worksheets.Count - 1].Cells[0, 0].Value = this.CaptionText;
        //        worksheets[worksheets.Count - 1].InsertDataTable(dtHead, "A2", false);
        //        worksheets[worksheets.Count - 1].InsertDataTable(dtTemp, "A3", false);
        //        for (int co = 0; co < dtHead.Columns.Count; co++)
        //        {
        //            int with = 0;
        //            if (this.TableStyles.Count > 0)
        //                with = (int)(this.TableStyles[0].GridColumnStyles[dtHead.Columns[co].ColumnName].Width);
        //            else
        //                with = (int)(this.Width / dtHead.Columns.Count);
        //            worksheets[worksheets.Count - 1].Columns[co].Width = this.TableStyles[0].GridColumnStyles[co].Width * 70;
        //            worksheets[worksheets.Count - 1].Cells[1, co].Style.Font.Color = Color.Blue;
        //            worksheets[worksheets.Count - 1].Cells[1, co].Style.Font.Italic = true;
        //            worksheets[worksheets.Count - 1].Cells[1, co].Style.Font.Size = (int)(worksheets[worksheets.Count - 1].Cells[1, co].Style.Font.Size * 1.2);

        //        }
        //        worksheets[worksheets.Count - 1].Rows[1].Height = (int)(worksheets[worksheets.Count - 1].Rows[1].Height * 1.5);
        //    }
        //    string fileName = dlg.FileName;
        //    if (fileName.IndexOf(".xls") == -1)
        //        fileName += ".xls";
        //    try
        //    {
        //        exFile.SaveXls(fileName);
        //        System.Diagnostics.Process.Start(fileName);
        //    }
        //    catch (Exception)
        //    {
        //        MessageBox.Show("Không thể Mở file Excel ngay lập tức \r\n Bạn phải đóng File Excel: " + fileName + " nếu nó đang được mở", "Thông báo lỗi");

        //    }
        //    #endregion

        //}
        //──────────────────────────────────────────────────────────────────   



        void mnExportToExel_Click(object sender, EventArgs e)
        {
            //this.ExportToExel();
        }
        //──────────────────────────────────────────────────────────────────   

        private void Draw()
        {
            if (isPaint == false) return;
            if (this.lstRowColor == null || lstRowColor.Count == 0) return;
            if (lstColumn == null || lstColumn.Count == 0) return;
            float x = 0, y = 0, with = 0, height = 0;
            {

                for (int i = 0; i < this.lstRowColor.Count; i++)
                {

                    for (int j = 0; j < this.TableStyles[0].GridColumnStyles.Count; j++)
                    {

                        y = 38 + (float)(lstRowColor[i].row * 17);
                        with = (float)(this.TableStyles[0].GridColumnStyles[j].Width);
                        height = 17;
                        Graphics G = this.CreateGraphics();
                        G.FillRectangle(lstRowColor[i].fillBrush, x + 1, y + 1, with - 2, height - 1);
                        G.DrawString(this[this.lstRowColor[i].row, j].ToString(), this.Font, lstRowColor[i].textBrush, x + 1, y + 3);

                        x += with;


                    }
                }
            }
            isPaint = false;
        }
        //──────────────────────────────────────────────────────────────────   

        public void FillColor(int row, Brush fillbrush, Brush textbrush)
        {
            if (lstRowColor == null) lstRowColor = new List<UserControls.rowColor>();
            UserControls.rowColor fRowColor = this.getRowColor(row);
            if (fRowColor != null)
            {
                fRowColor.textBrush = textbrush;
                fRowColor.fillBrush = fillbrush;
            }
            else
                lstRowColor.Add(new UserControls.rowColor(row, fillbrush, textbrush));
            isPaint = true;
            this.Draw();
        }
        //──────────────────────────────────────────────────────────────────   
        private UserControls.rowColor getRowColor(int row)
        {
            bool OK = false; int i = 0;
            while (i < lstRowColor.Count && !OK)
            {
                if (lstRowColor[i].row == row) OK = true;
                else i++;
            }
            if (OK) return lstRowColor[i];
            return null;
        }
        //──────────────────────────────────────────────────────────────────   
        public void FillColor(List<int> lstRow, List<Brush> lstFillbrush, List<Brush> lstTextbrush)
        {
            if (lstRowColor == null) lstRowColor = new List<UserControls.rowColor>();
            for (int i = 0; i < lstRow.Count; i++)
                this.lstRowColor.Add(new UserControls.rowColor(lstRow[i], lstFillbrush[i], lstTextbrush[i]));
            isPaint = true;
            this.Draw();
        }
        //──────────────────────────────────────────────────────────────────   
        public void setViewStyle(List<ColumnView> lst_lstColumn, System.Data.DataView dvLink)
        {
            MakeDataGridStyle(this, dvLink, lst_lstColumn);
            this.dvSource = dvLink;
            this.dvSource.AllowNew = this.allowNew;
            this.dvSource.AllowDelete = this.allowDelete;
            this.dvSource.AllowEdit = this.allowUpdate;
            this.lstColumn = lst_lstColumn;
            this.RowCount = dvSource.Count;
            this.ColumnCount = dvSource.Table.Columns.Count;
            //int n = this.CaptionText.IndexOf(",");
            //if (n > 1)
            //    this.CaptionText = this.CaptionText.Remove(n, 1);
            //this.CaptionText.Replace(",", "");
        }
        //──────────────────────────────────────────────────────────────────   
        public void setViewStyleExtent(List<ColumnView> lst_lstColumn, System.Data.DataView dvLink,DataTable dtCombobox,string Name,string Value)
        {
            MakeDataGridStyleExtent(this, dvLink, lst_lstColumn,dtCombobox,Name,Value);
            this.dvSource = dvLink;
            //this.dvSource.AllowNew = this.allowNew;
            //this.dvSource.AllowDelete = this.allowDelete;
            //this.dvSource.AllowEdit = this.allowUpdate;
            //this.lstColumn = lst_lstColumn;
            //this.RowCount = dvSource.Count;
            //this.ColumnCount = dvSource.Table.Columns.Count;
            //int n = this.CaptionText.IndexOf(",");
            //if (n > 1)
            //    this.CaptionText = this.CaptionText.Remove(n, 1);
            //this.CaptionText.Replace(",", "");
        }
        //──────────────────────────────────────────────────────────────────   
        public void setViewStyleColor(List<ColumnView> lst_lstColumn, System.Data.DataView dvLink)
        {
            MakeDataGridStyleColor(this, dvLink, lst_lstColumn);
            this.dvSource = dvLink;
            this.dvSource.AllowNew = this.allowNew;
            this.dvSource.AllowDelete = this.allowDelete;
            this.dvSource.AllowEdit = this.allowUpdate;
            this.lstColumn = lst_lstColumn;
            this.RowCount = dvSource.Count;
            this.ColumnCount = dvSource.Table.Columns.Count;
            //int n = this.CaptionText.IndexOf(",");
            //if (n > 1)
            //    this.CaptionText = this.CaptionText.Remove(n, 1);
            //this.CaptionText.Replace(",", "");
        }
        //──────────────────────────────────────────────────────────────────   
        
        //──────────────────────────────────────────────────────────────────   
        public void setDataSource(System.Data.DataView dvLink)
        {

            this.dvSource = dvLink;
            if (dvSource == null)
            {
                this.DataSource = null;
                this.RowCount = 0;
                this.ColumnCount = 0;
            }
            else
            {

                this.RowCount = dvSource.Count;
                this.dvSource.AllowNew = this.allowNew;
                this.dvSource.AllowDelete = this.allowDelete;
                this.dvSource.AllowEdit = this.allowUpdate;
                this.ColumnCount = dvSource.Table.Columns.Count;
                this.DataSource = dvSource;
                string s = this.CaptionText;
                int pos = s.IndexOf("; Số lượng: ");
                if (pos != -1) s = s.Remove(pos, s.Length - pos);
                //s += "; Số lượng: " + dvLink.Count.ToString();
                this.CaptionText = s;
            }
        }
        //──────────────────────────────────────────────────────────────────   
        private bool ExistColumns(string s_ColumnName)
        {
            int i = 0; bool temp = false;
            while (i < this.TableStyles[0].GridColumnStyles.Count && !temp)
            {
                if (this.TableStyles[0].GridColumnStyles[i].MappingName.ToLower() == s_ColumnName.ToLower()) temp = true;
                else i++;
            }
            return temp;
        }
       
        //──────────────────────────────────────────────────────────────────   
        private void MakeDataGridStyle(DataGrid dgView, System.Data.DataView dvLink, List<ColumnView> lstColumn)
        {

            dgView.TableStyles.Clear();
            
            DataGridTableStyle dgTableStyle = new DataGridTableStyle();
            dgTableStyle.MappingName = dvLink.Table.TableName;
            for (int i = 0; i < lstColumn.Count; i++)
            {
                if (lstColumn[i].isBit)
                {
                    DataGridBoolColumn bitdgCl = new DataGridBoolColumn();
                    bitdgCl.ReadOnly = lstColumn[i].IsReadOnly;
                    bitdgCl.NullText = "";
                    bitdgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                    bitdgCl.Alignment = HorizontalAlignment.Left;
                    bitdgCl.MappingName = lstColumn[i].clName;
                    bitdgCl.HeaderText = lstColumn[i].clNameVN;
                    dgTableStyle.GridColumnStyles.Add(bitdgCl);
                    

                }
                
                else
                {
                   
                        FormattableTextBoxColumn dgCl = new FormattableTextBoxColumn();
                        //DataGridTextBoxColumn dgCl = new DataGridTextBoxColumn();
                        dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                        if (lstColumn[i].Format != "")
                            dgCl.Format = lstColumn[i].Format;
                        dgCl.NullText = "";
                        dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                        dgCl.Alignment = HorizontalAlignment.Left;
                        dgCl.MappingName = lstColumn[i].clName;
                        dgCl.HeaderText = lstColumn[i].clNameVN;
                        dgCl.NullText = "";

                        dgTableStyle.GridColumnStyles.Add(dgCl);
                   
                }
            }
            dgView.TableStyles.Add(dgTableStyle);
            dgTableStyle.BackColor = dgView.BackColor;
            dgTableStyle.ForeColor = dgView.ForeColor;
            dgTableStyle.HeaderBackColor = dgView.HeaderBackColor;
            dgTableStyle.HeaderForeColor = dgView.HeaderForeColor;
            dgTableStyle.GridLineColor = dgView.GridLineColor;
            dgTableStyle.SelectionBackColor = dgView.SelectionBackColor;
            dgTableStyle.SelectionForeColor = dgView.SelectionForeColor;
            dgTableStyle.AlternatingBackColor = dgView.AlternatingBackColor;

            dgView.BorderStyle = BorderStyle.Fixed3D;
            dgView.FlatMode = false;


            



            dgView.DataSource = dvLink;
            string s = dgView.CaptionText;
            int pos = s.IndexOf(" ,Số lượng: ");
            if (pos != -1) s = s.Remove(pos, s.Length - pos);
            s += " ,Số lượng: " + dvLink.Count.ToString();
            dgView.CaptionText = s;
            try
            {
                if (dvLink.Count > 0) dgView.Select(dvLink.Count - 1);
            }
            catch (Exception) { }
        }

        //──────────────────────────────────────────────────────────────────   
        private void MakeDataGridStyleExtent(DataGrid dgView, System.Data.DataView dvLink, List<ColumnView> lstColumn,DataTable dtColumCombo,string Name,string Value)
        {

            dgView.TableStyles.Clear();

            DataGridTableStyle dgTableStyle = new DataGridTableStyle();
            dgTableStyle.MappingName = dvLink.Table.TableName;
            for (int i = 0; i < lstColumn.Count; i++)
            {
                if (lstColumn[i].isBit)
                {
                    DataGridBoolColumn bitdgCl = new DataGridBoolColumn();
                    bitdgCl.ReadOnly = lstColumn[i].IsReadOnly;
                    bitdgCl.NullText = "";
                    bitdgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                    bitdgCl.Alignment = HorizontalAlignment.Left;
                    bitdgCl.MappingName = lstColumn[i].clName;
                    bitdgCl.HeaderText = lstColumn[i].clNameVN;
                    dgTableStyle.GridColumnStyles.Add(bitdgCl);


                }

                else
                {
                    if (lstColumn[i].Style == "Combobox")
                    {
                        DataGridComboBoxColumn dgCl = new DataGridComboBoxColumn();
                            //lstColumn[i].clName, dtColumCombo, Name, Value, dgView);
                        dgCl.ComboBox.DataSource = dtColumCombo;
                        dgCl.ComboBox.DisplayMember = Name;
                        dgCl.ComboBox.ValueMember = Value;
                        //dgCl.ComboBox.AutoCompleteMode = AutoCompleteMode.Suggest; 
                        
                        dgCl.HeaderText = lstColumn[i].clNameVN;
                        dgCl.MappingName = lstColumn[i].clName;
                        dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                        dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                        dgTableStyle.GridColumnStyles.Add(dgCl);
                    }
                    else if (lstColumn[i].Style == "Button")
                    {
                        DataGridButtonColumn dgCl = new DataGridButtonColumn(i);
                        //lstColumn[i].clName, dtColumCombo, Name, Value, dgView);
                      
                        dgCl.HeaderText = lstColumn[i].clNameVN;
                        dgCl.MappingName = lstColumn[i].clName;
                        dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                        dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                        dgCl.CellButtonClicked +=
                        new DataGridCellButtonClickEventHandler(HandleCellButtonClick);

                        dgTableStyle.GridColumnStyles.Add(dgCl);

                        dgView.MouseDown += new MouseEventHandler(dgCl.HandleMouseDown);
                        dgView.MouseUp += new MouseEventHandler(dgCl.HandleMouseUp);
					
                    }
                    else if (lstColumn[i].Style == "DateTime")
                    {
                        DataGridTimePickerColumn dgCl = new DataGridTimePickerColumn();
                        dgCl.HeaderText = lstColumn[i].clNameVN;
                        dgCl.MappingName = lstColumn[i].clName;
                        //dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                        dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                        dgTableStyle.GridColumnStyles.Add(dgCl);
                    }
                    else
                    {
                        FormattableTextBoxColumn dgCl = new FormattableTextBoxColumn();
                        //DataGridTextBoxColumn dgCl = new DataGridTextBoxColumn();
                        dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                        if (lstColumn[i].Format != "")
                            dgCl.Format = lstColumn[i].Format;
                        dgCl.NullText = "";
                        dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                        dgCl.Alignment = HorizontalAlignment.Left;
                        dgCl.MappingName = lstColumn[i].clName;
                        dgCl.HeaderText = lstColumn[i].clNameVN;
                        dgCl.NullText = "";

                        dgTableStyle.GridColumnStyles.Add(dgCl);
                    }
                }
            }
            dgView.TableStyles.Add(dgTableStyle);
            dgTableStyle.BackColor = dgView.BackColor;
            dgTableStyle.ForeColor = dgView.ForeColor;
            dgTableStyle.HeaderBackColor = dgView.HeaderBackColor;
            dgTableStyle.HeaderForeColor = dgView.HeaderForeColor;
            dgTableStyle.GridLineColor = dgView.GridLineColor;
            dgTableStyle.SelectionBackColor = dgView.SelectionBackColor;
            dgTableStyle.SelectionForeColor = dgView.SelectionForeColor;
            dgTableStyle.AlternatingBackColor = dgView.AlternatingBackColor;

            dgView.BorderStyle = BorderStyle.Fixed3D;
            dgView.FlatMode = false;






            dgView.DataSource = dvLink;
            string s = dgView.CaptionText;
            int pos = s.IndexOf(" ,Số lượng: ");
            if (pos != -1) s = s.Remove(pos, s.Length - pos);
            s += " ,Số lượng: " + dvLink.Count.ToString();
            dgView.CaptionText = s;
            try
            {
                if (dvLink.Count > 0) dgView.Select(dvLink.Count - 1);
            }
            catch (Exception) { }
        }
        // handler for a click on one of the gridcell buttons
        private void HandleCellButtonClick(object sender, DataGridCellButtonClickEventArgs e)
        {
            MessageBox.Show("row " + e.RowIndex.ToString() + " will be deleted.");
        }
        private void MakeDataGridStyleColor(DataGrid dgView, System.Data.DataView dvLink, List<ColumnView> lstColumn)
        {

            dgView.TableStyles.Clear();

            DataGridTableStyle dgTableStyle = new DataGridTableStyle();
            dgTableStyle.MappingName = dvLink.Table.TableName;
            for (int i = 0; i < lstColumn.Count; i++)
            {
                if (lstColumn[i].isBit)
                {
                    DataGridBoolColumn bitdgCl = new DataGridBoolColumn();
                    bitdgCl.ReadOnly = lstColumn[i].IsReadOnly;
                    bitdgCl.NullText = "";
                    bitdgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                    bitdgCl.Alignment = HorizontalAlignment.Left;
                    bitdgCl.MappingName = lstColumn[i].clName;
                    bitdgCl.HeaderText = lstColumn[i].clNameVN;
                    dgTableStyle.GridColumnStyles.Add(bitdgCl);


                }
                else
                {
                    FormattableTextBoxColumn dgCl = new FormattableTextBoxColumn();
                    //DataGridTextBoxColumn dgCl = new DataGridTextBoxColumn();
                    dgCl.ReadOnly = lstColumn[i].IsReadOnly;
                    if (lstColumn[i].Format != "")
                        dgCl.Format = lstColumn[i].Format;
                    dgCl.NullText = "";
                    dgCl.Width = (int)(dgView.Width * lstColumn[i].Percent);
                    dgCl.Alignment = HorizontalAlignment.Left;
                    dgCl.MappingName = lstColumn[i].clName;
                    dgCl.HeaderText = lstColumn[i].clNameVN;
                    dgCl.NullText = "";
                    dgCl.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
                    dgTableStyle.GridColumnStyles.Add(dgCl);
                }
            }
            dgView.TableStyles.Add(dgTableStyle);
            dgTableStyle.BackColor = dgView.BackColor;
            
            dgTableStyle.HeaderBackColor = dgView.HeaderBackColor;
            dgTableStyle.HeaderForeColor = dgView.HeaderForeColor;
            dgTableStyle.GridLineColor = dgView.GridLineColor;
            dgTableStyle.SelectionBackColor = dgView.SelectionBackColor;
            dgTableStyle.SelectionForeColor = dgView.SelectionForeColor;
            dgTableStyle.AlternatingBackColor = dgView.AlternatingBackColor;

            dgView.BorderStyle = BorderStyle.Fixed3D;
            dgView.FlatMode = false;






            dgView.DataSource = dvLink;
            string s = dgView.CaptionText;
            int pos = s.IndexOf(" ,Số lượng: ");
            if (pos != -1) s = s.Remove(pos, s.Length - pos);
            s += " ,Số lượng: " + dvLink.Count.ToString();
            //dgView.CaptionText = s;
            try
            {
                if (dvLink.Count > 0) dgView.Select(dvLink.Count - 1);
            }
            catch (Exception) { }
        }
        public List<ColorView> lstColor = new List<ColorView>();
        private void SetCellFormat(object sender, DataGridFormatCellEventArgs e)
        {
            //Brush blue = new SolidBrush(System.Drawing.Color.FromArgb(91,132,200));
            //Brush cyan = new SolidBrush(System.Drawing.Color.FromArgb(104, 155, 47));
            //Brush red = new SolidBrush(System.Drawing.Color.FromArgb(219, 92, 53));
            CurrencyManager cm = (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember];
            DataView dview = (DataView)cm.List;
            for(int i =0;i<lstColor.Count;i++)
            {
                if (dview[e.Row][ColName].ToString() == lstColor[i].Status.ToString())
                {
                    e.BackBrush = lstColor[i].Color;
                }
            }
            
        }
       


        //──────────────────────────────────────────────────────────────────   
        public void TakeAutoNumber()
        {
            DataTable dt = this.dvSource.Table;
            if (dt == null) return;
            string s = "0";
            if (dt.Columns.IndexOf("STT") == -1)
            {
                dt.Columns.Add("STT", s.GetType());
            }
            for (int i = 0; i < dvSource.Count; i++)
                dvSource[i]["STT"] = (i + 1).ToString();

        }
        public void TakeAutoNumberReport()
        {
            DataTable dt = this.dvSource.Table;
            if (dt == null) return;
            string s = "0";
            if (dt.Columns.IndexOf("STT") == -1)
            {
                dt.Columns.Add("STT", s.GetType());
            }
            for (int i = 0; i < dvSource.Count-1; i++)
                dvSource[i]["STT"] = (i + 1).ToString();

        }
        //──────────────────────────────────────────────────────────────────   
        public void SelectOne(int row)
        {
            if (this.dvSource == null || this.dvSource.Count == 0) return;
            if (this.dvSource.Count <= row || row < 0) return;
            for (int i = 0; i < this.RowCount; i++)
            {
                this.UnSelect(i);
            }
            this.CurrentRowIndex = row; ;
            this.Select(row);
        }
        //──────────────────────────────────────────────────────────────────   

        void mnDeleteOhterRow_Click(object sender, EventArgs e)
        {
            if (dvSource == null || dvSource.Count == 0) return;
            dvSource.AllowDelete = true;
            DataTable RootTB = this.dvSource.Table;
            DataTable TempTB = RootTB.Copy();
            TempTB.Rows.Clear();


            for (int j = 0; j < RootTB.Rows.Count; j++)
                if (this.IsSelected(j))
                {
                    hsTool.dt_Copy(RootTB, j, ref TempTB);
                }
            RootTB = TempTB.Copy();
            this.DataSource = RootTB.DefaultView;

            dvSource.AllowDelete = false;

        }
        //──────────────────────────────────────────────────────────────────   
        void mnDeleteChosenRow_Click(object sender, EventArgs e)
        {
            if (dvSource == null || dvSource.Count == 0) return;
            dvSource.AllowDelete = true;
            DataTable RootTB = this.dvSource.Table;
            DataTable TempTB = RootTB.Copy();
            TempTB.Rows.Clear();


            for (int j = 0; j < RootTB.Rows.Count; j++)
                if (!this.IsSelected(j))
                {

                    hsTool.dt_Copy(RootTB, j, ref TempTB);
                }

            RootTB = TempTB.Copy();
            this.DataSource = RootTB.DefaultView;

            dvSource.AllowDelete = false;
        }
        //──────────────────────────────────────────────────────────────────   
        public int SearchValue(int columnIndex, string s_Value)
        {
            if (this.dvSource == null || dvSource.Count == 0) return -1;
            int i = 0, temp = 0;
            while (i < dvSource.Count && temp == 0)
            {
                if (this[i, columnIndex].ToString().ToLower() == s_Value.ToLower())
                    temp = 1;
                else i++;
            }
            if (temp == 1)
            {
                this.SelectOne(i);
                return i;
            }
            return -1;        
            
        }
        //────────────────────────────────────────────────────────────────── 
        #region Start Code Of 
        //=========================================== => Phan biet cac ham
        /// <summary>
        /// Lấy bảng thông tin dữ liệu trên lưới.
        /// </summary>
        /// <param name="dgView"></param>
        /// <returns></returns>
        public DataTable GetDataSource_FromHSDatagrid()
        {
            DataTable dt = null;
            try
            {
                //------------------------------------------------
                // Case 1:
                if (this.DataSource == null) return null;
                if (this.DataSource.GetType().ToString() == "System.Data.DataView")
                {
                    DataView dvTemp = (DataView)this.DataSource;
                    dt = dvTemp.Table;
                }
                else dt = (DataTable)this.DataSource;

                //------------------------------------------------
                // Case 2:
                //CurrencyManager cm1 = (CurrencyManager)this.BindingContext[this.hsdg_ThongTinThuTienInHoaDon_ThuTien.DataSource, this.hsdg_ThongTinThuTienInHoaDon_ThuTien.DataMember];
                //DataView dvLuoiHienThiThongTinThuTien_InHoaDon = (DataView)cm1.List;
                //this._dtLuoiThuTienVaInHoaDon = dvLuoiHienThiThongTinThuTien_InHoaDon.Table;
            }
            catch (Exception) { }
            return dt;
        }
        //=========================================== => Phan biet cac ham
        /// <summary>
        /// Khởi tạo định dạng tên cột, kích thước cột và hiển thị dữ liệu
        /// </summary>
        /// <param name="BangMacDinh"></param>
        /// <param name="BangDeHienThi"></param>
        /// <param name="ListC"></param>
        public void KhoiTaoDataGrid(DataTable dtBangMacDinh, DataTable dtBangDeHienThi, List<ColumnView> ListC)
        {
            // Verify available data
            if (dtBangDeHienThi == null)
            {
                this.DinhDangCot_VaGanBangHienThi(dtBangMacDinh, ListC);
            }
            else
            {
                // Nếu bảng hiển thị null, hoặc rỗng không co dòng nào
                if (dtBangDeHienThi == null || dtBangDeHienThi.Rows.Count <= 0)
                {
                    this.DinhDangCot_VaGanBangHienThi(dtBangMacDinh, ListC);
                }
                else
                {
                    this.DinhDangCot_VaGanBangHienThi(dtBangDeHienThi, ListC);
                }
            }
        }

        //----------------------------------------------OK
        //
        /// <summary>
        /// Định dạng cột và gán bảng hiển thị cho hsDataGrid
        /// </summary>
        /// <param name="hsdgView"></param>
        /// <param name="dtSource"></param>
        /// <param name="lstC"></param>
        private void DinhDangCot_VaGanBangHienThi(DataTable dtSource, List<ColumnView> lstC)
        {
            #region Định dạng tên cột và kích thước cột cho DataView

            // Chuyển đổi kiếu dữ liệu để hiển thị lên lưới.
            DataView dvSource = dtSource.DefaultView;

            // Kiem tra bang hien thi neu khac null
            if (dvSource != null)
            {
                // Neu Style bang hien thi cua DataGrid chua co
                if (this.TableStyles.Count == 0)
                {
                    // Set kieu bang hien thi va noi dung bang hien thi
                    this.setViewStyle(lstC, dvSource);
                }
                else
                {
                    // Set noi dung bang hien thi
                    this.setDataSource(dvSource);
                } // End else
            }

            #endregion Định dạng tên cột và kích thước cột cho DataView
        }

        //----------------------------------------------OK
        /// <summary>
        /// Get the current row of the datagrid.
        /// </summary>
        /// <returns></returns>
        public DataRow GetDataCurrentRow()
        {
            CurrencyManager xCM =
                (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember];
            DataRowView xDRV = (DataRowView)xCM.Current;
            return xDRV.Row;
        }

        //----------------------------------------------OK
        /// <summary>
        /// Get indexes the current selected rows.
        /// </summary>
        /// <returns></returns>
        public ArrayList GetSelectedRows()
        {
            ArrayList al = new ArrayList();
            CurrencyManager cm =
                 (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember];
            DataView dv = (DataView)cm.List;
            for (int i = 0; i < dv.Count; ++i)
            {
                if (this.IsSelected(i))
                    al.Add(i);
            }
            return al;
        }

        //----------------------------------------------OK
        /// <summary>
        /// Clear all data is showed on hsDataGrid.
        /// </summary>
        /// <param name="dtShow"></param>
        /// <param name="lstC"></param>
        public void Clear(DataTable dtShow, List<ColumnView> lstC)
        {
            DataTable dtBangHienThi = new DataTable();
            // Hiển thị lưới Lịch Sử Dịch Vụ
            KhoiTaoDataGrid(dtShow, dtBangHienThi, lstC);
        }
        #endregion Start Code Of Thanh Hải.

   

    }//end class
}
